package com.byq.mm.application.cluster.server;

import java.util.ArrayList;


import com.byq.mm.abstractx.cluster.server.executor.Executor;
import com.byq.mm.abstractx.device.Device;
import com.byq.mm.abstractx.engine.CoreEnvironment;
import com.byq.mm.abstractx.protocol.Interaction;
import com.byq.mm.application.cluster.provider.LevelControlProvider;
import com.byq.mm.application.cluster.provider.OnoffProvider;
import com.byq.mm.application.cluster.server.executor.LevelControlExecutor;

import com.byq.mm.application.cluster.server.executor.OnoffExecutor;
import com.byq.mm.foundation.cluster.datatype.AttributeValue;
import com.byq.mm.foundation.cluster.datatype.BooleanValue;
import com.byq.mm.foundation.cluster.datatype.DoubleRangeValue;
import com.byq.mm.foundation.cluster.datatype.DoubleValue;
import com.byq.mm.foundation.cluster.server.BasicClusterServer;

public class OnoffServer extends BasicClusterServer{

	public OnoffServer(String cluster, Device device, CoreEnvironment env) {
		super(cluster, device, env);
		attributes.put(OnoffProvider.Define.Attributes.ONOFF, new BooleanValue(false));
	}
	public BooleanValue getOnOff(){
		return (BooleanValue)attributes.get(OnoffProvider.Define.Attributes.ONOFF);
	}
	@Override
	protected Class<? extends AttributeValue> getAttributeType(String attributeName) {
		if(attributeName.equals(OnoffProvider.Define.Attributes.ONOFF))
			return BooleanValue.class;
		return null;
	}
	@Override
	public boolean onCommand(Interaction i, String from) {
		if(super.onCommand(i, from))
			return true;
		
		
		Executor e = super.getExecutor();
		if(e instanceof OnoffExecutor){
			
			OnoffExecutor oe = (OnoffExecutor)e;
			if(i.command.equals(OnoffProvider.Define.ClientCommand.TOGGLE)){
				toggle(oe);
				return true;
			}
		}
		return false;
		
		
		
	}
	void on(OnoffExecutor oe){

		BooleanValue onoff = getOnOff();
		onoff.setValue(true);
		
		broadcastAttributeToAll(OnoffProvider.Define.Attributes.ONOFF);
		
	oe.on();
	}
	void off(OnoffExecutor oe){

		BooleanValue onoff = getOnOff();
		onoff.setValue(false);
		
		broadcastAttributeToAll(OnoffProvider.Define.Attributes.ONOFF);
		Executor e = super.getExecutor();
		oe.off();

	}
	void toggle(OnoffExecutor oe){

		BooleanValue onoff = getOnOff();
		onoff.toggle();
		broadcastAttributeToAll(OnoffProvider.Define.Attributes.ONOFF);
		oe.toggle();


	}
	public void onChange(boolean value){
		
		BooleanValue onoff = getOnOff();
		onoff.setValue(value);
		broadcastAttributeToAll(OnoffProvider.Define.Attributes.ONOFF);

	}
	
	protected void broadcast(Interaction i){
		env.getExtensionManager().broadcastInteraction(i,this.getAccessController().getWhileList());
	}
	@Override
	protected void init() {
		attributes.put(OnoffProvider.Define.Attributes.ONOFF,new BooleanValue(false));
		subscriber.put(OnoffProvider.Define.Attributes.ONOFF,  new ArrayList<String>());
		
	}

	

}
